package com.elantra.controller;

import com.elantra.base.BaseClass;
import com.elantra.base.SystemManage;
import com.elantra.util.PropertiesUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
public class WebController extends BaseClass {

    @RequestMapping(value = "/web/{file}.do")
    public ModelAndView web1(HttpServletRequest req, HttpServletResponse resp, @PathVariable("file") String file) throws Exception {

        return web(req, resp, null, file);
    }

    @RequestMapping(value = "/web/{dir}/{file}.do")
    public ModelAndView web2(HttpServletRequest req, HttpServletResponse resp,
                             @PathVariable("dir") String dir, @PathVariable("file") String file) throws Exception {
        return web(req, resp, dir, file);
    }

    private ModelAndView web(HttpServletRequest req, HttpServletResponse resp, String dir, String file) {
        ModelAndView mv = new ModelAndView();
        dir = dir == null ? "" : dir.trim();
        file = file == null ? "" : file.trim();
        if (!dir.isEmpty() && !file.isEmpty()) {
            mv.setViewName("web/" + dir + "/" + file);
        } else if (dir.isEmpty() && !file.isEmpty()) {
            mv.setViewName("web/" + file);
        }
        Map upMap = new HashMap();
        Map map = req.getParameterMap();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            String[] values = (String[]) map.get(key);
            String val = "";
            for (int i = 0; i < values.length; i++) {
                if (values[i] != null) {
                    val = values[i].trim();
                    if (i < values.length - 1) {
                        val += ",";
                    }
                }
            }
            upMap.put(key, val);
        }

//        mv.addObject("hvServer", PropertiesUtil.getValue("hvServer"));
        mv.addObject("basePath", req.getContextPath());
//        mv.addObject("upMap", upMap);
        mv.addObject("cUser", SystemManage.getInstance().getSysUser());
        mv.addObject("token", SystemManage.getInstance().getCurrentRequest().getRequestedSessionId());
        return mv;
    }

}
